package com.seaside.park.api;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import com.seaside.parkCommon.service.AlarmService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.seaside.common.bean.Result;
import com.seaside.parkCommon.bean.Alarm;
import com.seaside.parkCommon.bean.AlarmOperate;
import com.seaside.parkCommon.bean.User;
import com.seaside.parkCommon.mapper.AlarmOperateMapper;
import com.seaside.parkCommon.mapper.UserMapper;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

@Api(tags="告警展示")
@RestController
@RequestMapping("/api/alarm")
public class AlarmAPI {

    @Autowired
    private AlarmService alarmService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AlarmOperateMapper alarmOperateMapper;

    @ApiOperation(value = "告警列表", response = Result.class)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="header",name="bearer",dataTypeClass=String.class,required=true,value="用户token"),
            @ApiImplicitParam(paramType="query",name="curpage",dataTypeClass=Integer.class,required=true,value="当前页")
    })
    @PostMapping("/list")
    public Result<IPage<Alarm>> list(@ApiIgnore Authentication auth, int curpage) {

        Page<Alarm> page = new Page<>(curpage, 15, false);

        User user = userMapper.selectById(auth.getName());
        if (user == null) {
        	return Result.Error("未找到该用户！");
        }

        QueryWrapper<Alarm> queryWrapper = new QueryWrapper<>();
        if ("manager".equals(user.getUserType())) {
        	queryWrapper.eq("create_user_id", user.getParkZoneId());
        } else if ("user".equals(user.getUserType())) {
        	queryWrapper.eq("user_name", user.getUserName());
        } else {
        	return Result.Error("无权查看！");
        }

        queryWrapper.in("exception_type", Arrays.asList(0, 1));		// 0：标识非订单车停放，1：标识临停错误
        queryWrapper.eq("handle_status", 0);						// 0：待处理

        queryWrapper.orderByDesc("time");

        Result<IPage<Alarm>> iPageRet = alarmService.getAlarmListPage(page, queryWrapper);
        if (iPageRet.isSucess()) {
        	IPage<Alarm> alarmPage = iPageRet.getData();
        	return Result.OK("", alarmPage.getRecords());
        }
        return Result.Error(iPageRet.getMsg());
    }

    @ApiOperation(value = "告警分页列表", response = Result.class)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="header",name="bearer",dataTypeClass=String.class,required=true,value="用户token"),
            @ApiImplicitParam(paramType="query",name="curpage",dataTypeClass=Integer.class,required=true,value="当前页")
    })
    @PostMapping("/page")
    public Result<IPage<Alarm>> getAlarmListPage(@ApiIgnore Authentication auth, int curpage) {

        Page<Alarm> page = new Page<>(curpage, 15, false);

        User user = userMapper.selectById(auth.getName());
        if (user == null) {
        	return Result.Error("未找到该用户！");
        }

        QueryWrapper<Alarm> queryWrapper = new QueryWrapper<>();
        if ("manager".equals(user.getUserType())) {					// 物业管理可查看停车场所有告警，并可处理
        	queryWrapper.eq("park_zone_no", user.getParkZoneId());
        } else if ("user".equals(user.getUserType())) {				// 注册用户可查看自己名下绑定车位相关的告警
        	queryWrapper.eq("user_name", user.getUserName());
        } else {
        	return Result.Error("无权查看！");
        }

        queryWrapper.in("exception_type", Arrays.asList(0, 1));		// 0：标识非订单车停放，1：标识临停错误
        queryWrapper.eq("handle_status", 0);						// 0：待处理

        queryWrapper.orderByDesc("time");

        Result<IPage<Alarm>> iPageRet = alarmService.getAlarmListPage(page, queryWrapper);

        return iPageRet;
    }

    @ApiOperation(value = "告警处理", response = Result.class)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="header",name="bearer",dataTypeClass=String.class,required=true,value="用户token"),
            @ApiImplicitParam(paramType="query",name="alarmId",dataTypeClass=Integer.class,required=true,value="告警ID"),
            @ApiImplicitParam(paramType="query",name="handleType",dataTypeClass=Integer.class,required=true,value="处理方式（1：电话，2：挪车，3：锁车）")
    })
    @PostMapping("/handle")
    public Result<Boolean> doAlarmHandle(@ApiIgnore Authentication auth,
    		@RequestParam Integer alarmId,
    		@RequestParam Integer handleType) {

    	if (alarmId == null || handleType == null) {
    		return Result.Error("参数错误！");
    	}

        User user = userMapper.selectById(auth.getName());
        if (user == null) {
        	return Result.Error("用户错误！");
        }

    	Result<Alarm> alarmRet = alarmService.getById(alarmId);
    	if (!alarmRet.isSucess()) {
            return Result.Error(alarmRet.getMsg());
    	}

    	Alarm alarm = alarmRet.getData();
    	if (alarm.getHandleStatus() == 0) {				// 待处理
    		if (handleType != 4 && handleType != 1) {
    			return Result.Error("非法处理状态！");
    		}
    	} else if (alarm.getHandleStatus() == 1) {		// 已打电话
    		if (handleType != 4 && handleType != 2) {
    			return Result.Error("非法处理状态！");
    		}
    	} else if (alarm.getHandleStatus() == 2) {		// 已锁车
    		if (handleType != 4 && handleType != 3) {
    			return Result.Error("非法处理状态！");
    		}
    	} else if (alarm.getHandleStatus() == 3) {		// 已挪车
    		if (handleType != 4) {
    			return Result.Error("非法处理状态！");
    		}
    	} else {										// 异常数据
    		return Result.Error("告警处理已结束！");
    	}

    	// 保存操作记录
    	AlarmOperate operate = new AlarmOperate();
    	operate.setAlarmId(alarmId);
    	operate.setHandler(user.getUserName());
    	operate.setHandleStatus(handleType);
    	operate.setHandleTime(new Date());
    	alarmOperateMapper.insert(operate);

    	// 更新新的状态
		alarm.setHandleStatus(handleType);
		return alarmService.updateAlarm(alarm);
    }

    @ApiOperation(value = "查询告警处理过程", response = Result.class)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="header",name="bearer",dataTypeClass=String.class,required=true,value="用户token"),
            @ApiImplicitParam(paramType="query",name="alarmId",dataTypeClass=Integer.class,required=true,value="告警ID")
    })
    @PostMapping("/operate/list")
    public Result<List<AlarmOperate>> getAlarmOperateList(@ApiIgnore Authentication auth,
    		@RequestParam Integer alarmId) {

    	if (alarmId == null) {
    		return Result.Error("参数错误！");
    	}

    	QueryWrapper<AlarmOperate> queryWrapper = new QueryWrapper<>();
    	queryWrapper.eq("alarm_id", alarmId);
    	queryWrapper.orderByDesc("handle_time");
    	List<AlarmOperate> operateList = alarmOperateMapper.selectList(queryWrapper);

    	return Result.OK("查询成功！", operateList);
    }

    @ApiOperation(value = "小程序推送告警", response = Result.class)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query",name="alarm",dataTypeClass=Alarm.class,required=true,value="告警实体")
    })
    @PostMapping("/movement")
    public Result movement(Alarm alarm) {
        alarm.setTime(new Date());
        if (alarmService.save(alarm)){
            return Result.OK("推送成功！");
        }
        return Result.Error("推送失败!");
    }
}
